package com.zlp.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author:ZouXiangHui
 * @Description:设置全局UTF-8编码
 * @time:2018年9月18日 下午1:16:23
 */
public class CharacterEncodingFilter implements Filter {
	private String encode = "UTF-8";// 默认UTF-8编码
	
	public void init(FilterConfig filterConfig) throws ServletException {
		String encoding = filterConfig.getInitParameter("encode");
		if (encoding != null) {
			encode = encoding;
		}
	}
    
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;

		// 设置request编码
		request.setCharacterEncoding(encode);
		// 设置相应信息
		response.setContentType("text/html;charset=" + encode);
		response.setCharacterEncoding(encode);

		chain.doFilter(new CharacterEncodingRequest(request), response);

	}
    
	public void destroy() {

	}

}

/**
 * 对Get方式传递的请求参数进行编码
 */
@SuppressWarnings("all")
class CharacterEncodingRequest extends HttpServletRequestWrapper {
	private HttpServletRequest request = null;

	public CharacterEncodingRequest(HttpServletRequest request) {
		super(request);
		this.request = request;
	}


}